package acn.spring.core.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import acn.spring.domain.Item;

public class SimpleInterceptor implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		if("addItem".equalsIgnoreCase(methodInvocation.getMethod().getName())) {
			if(methodInvocation.getArguments().length == 1 && 
					methodInvocation.getArguments()[0] instanceof Item) {
				Item item = (Item) methodInvocation.getArguments()[0];
				if(item.getId() != 0) {
					throw new RuntimeException("before: cannot be persistent. id is not 0");
				}
			}
		}
		
		Object result = methodInvocation.proceed();
		if(result instanceof Item) {
			Item item = (Item) result;
			if(item.getId() == 0) {
				throw new RuntimeException("after: couldnot be persistent. id is 0");
			}
		}
		return result;
	}

}
